<script lang="ts" setup>
  import { reactive, ref } from 'vue'
  import userService from '@/api/userService'
  import { useRouter } from 'vue-router'
  import appStore from '@/store'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import userType from '@/tips/userType.json'
  import activation from '@/tips/activation.json'
  import mitt from '@/utils/mitt'
  const userTypeData: { [key: string]: string } = reactive(userType)
  const activationData: { [key: string]: string } = reactive(activation)
  interface apiData {
    user_id: 'string'
    domain_name: 'string'
    project_id: 'string'
    access_key: 'string'
    secret_access_key: 'string'
    region: 'string'
    keypair_name: 'string'
  }
  let tableData: apiData[] = reactive([])
  const basic = {
    username: '用户名',
    user_type: '用户类型',
    activation: '激活状态',
    phone: '电话',
    email: '邮箱'
  }
  let basicData: { [key: string]: { [key: string]: string } } = reactive({ data: {} })
  let insertData = ref({} as { [key: string]: string })
  const router = useRouter()
  const buildInsertResourceConfig = () => {
    router.push({ name: 'insertResourceConfig' })
  }
  const param = reactive({
    project_id: appStore.userStore.project_id,
    offset: 1,
    limit: 10,
    id: ''
  })

  const toDetails = (data: any) => {
    let obj = JSON.stringify(data)
    router.push({
      name: 'resconfigDetails',
      params: {
        Rdata: encodeURIComponent(obj)
      }
    })
  }
  let tableTotal = ref(0)
  const getResconfig = async () => {
    let res = await userService.getUserResconfig(param)
    tableTotal.value = res.data.total
    tableData.length = 0
    tableData.push(...res.data.res_conf_list)
  }
  const deleteOrigin = (id: any, name: any) => {
    ElMessageBox.confirm(`确认删除此条数据？\n租户名: ${name}\nID: ${id}`, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        let res = await userService.deleteResconfig(id)
        if (res.status < 300) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          mitt.emit('getRegion')
          getResconfig()
        } else {
          ElMessage({
            type: 'info',
            message: '删除失败'
          })
        }
      })
      .catch(() => {})
  }
  const small = ref(false)
  const disabled = ref(false)
  const background = ref(true)
  const handleSizeChange = (val: number) => {
    param.limit = val
    param.offset = 1
    getResconfig()
  }
  const handleCurrentChange = (val: number) => {
    param.offset = val
    getResconfig()
  }
  const getUserInfo = async () => {
    let res = await userService.getUserInfo(insertData.value.id)
    basicData.data = res.data
  }
  let showEdit = ref({
    Phone: false,
    Email: false
  } as { [key: string]: boolean })
  const changeUser = (key: string) => {
    for (const k in showEdit.value) {
      if (k != key) {
        showEdit.value[k] = false
      }
    }
    showEdit.value[key] = true
  }
  const closeRow = async (key: string) => {
    await getUserInfo()
    showEdit.value[key] = false
  }

  const onSubmit = async (key: string) => {
    let data = {
      resconfig: {
        Phone: '',
        Email: ''
      }
    }
    data.resconfig = JSON.parse(JSON.stringify(basicData.data))
    let phone = new RegExp(/^(1[2-9][0-9])\d{8}$/)
    let email = new RegExp(/^\w+@\w+(\.\w+)+$/)
    if (data.resconfig.Phone) {
      let result = phone.test(data.resconfig.Phone)
      if (!result) {
        ElMessage({
          message: '请填写正确的电话号码',
          type: 'warning'
        })
        return false
      }
    }
    if (data.resconfig.Email) {
      let result = email.test(data.resconfig.Email)
      if (!result) {
        ElMessage({
          message: '请填写正确的邮箱',
          type: 'warning'
        })
        return false
      }
      if (!result) return false
    }

    try {
      let res = await userService.changeUser(data)
      if (res.status < 300) {
        ElMessage({
          message: '修改成功',
          type: 'success'
        })
        closeRow(key)
        getResconfig()
      }
    } catch (err) {
      ElMessage.error('创建失败')
    }
  }

  if (localStorage.getItem('insertData')) {
    insertData.value = JSON.parse(localStorage.getItem('insertData') as string)
    param.id = insertData.value.id
    getResconfig()
    getUserInfo()
  }
  const backUserInfo = () => {
    router.push({ name: 'userMgmtList' })
  }
</script>
<template>
  <div id="user-info">
    <div class="run-box">
      <div class="state-box">
        <div class="run-label">
          <span class="run-name-box">{{ insertData.name }}</span
          >账号信息
          <span class="back" @click="backUserInfo">&lt;&nbsp;返回</span>
        </div>
      </div>
    </div>
    <div class="basic-info">
      <div class="basic-title">基本信息</div>
      <div class="basic-box">
        <div class="content-box" v-for="(item, key) in basic" :key="key">
          <div class="in-box" v-if="key == 'username'">
            <div class="content-label">{{ item }}</div>
            <div class="content-text">{{ basicData.data[key] || '--' }}</div>
          </div>
          <div class="in-box" v-else-if="key == 'user_type'">
            <div class="content-label">{{ item }}</div>
            <div class="content-text">{{ userTypeData[`${basicData.data[key]}`] || '--' }}</div>
          </div>
          <div class="in-box" v-else-if="key == 'activation'">
            <div class="content-label">{{ item }}</div>
            <div class="content-text">{{ activationData[`${basicData.data[key]}`] || '--' }}</div>
          </div>
          <div class="in-box" v-else>
            <div class="content-label">{{ item }}</div>
            <div class="content-text" v-if="!showEdit[key]">{{ basicData.data[key] || '--' }}</div>
            <div class="content-text" v-else>
              <el-input v-model="basicData.data[key]" />
            </div>
            <div class="edit">
              <div v-if="!showEdit[key]" class="actions-box">
                <div class="actions-details" @click="changeUser(key)">修改</div>
              </div>
              <div v-else class="actions-box">
                <div class="actions-details" @click="onSubmit(key)">保存</div>
                <div class="line"></div>
                <div class="actions-details" @click="closeRow(key)">取消</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="insert-info">
      <div class="insert-top">
        <div class="insert-title">资源租户信息</div>
        <button class="btn" @click="buildInsertResourceConfig">新增租户</button>
      </div>
      <div class="insert-table">
        <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#f4f5f8', color: '#252b3a' }" :border="true">
          <el-table-column label="用户名" width="200">
            <template #default="scope">
              <div class="id-box">
                {{ scope.row.username }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="租户标识">
            <template #default="scope">
              <div class="id-box">
                {{ scope.row.ori_project_id }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="domain_name" label="租户名称" />
          <el-table-column label="项目id">
            <template #default="scope">
              <div class="id-box">
                {{ scope.row.project_id }}
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180" v-if="appStore.userStore.UserType === 9">
            <template #default="scope">
              <div class="actions-box">
                <div class="actions-details" @click="toDetails(scope.row)">详情</div>
                <div class="line"></div>
                <div class="actions-delete" @click="deleteOrigin(scope.row.id, scope.row.domain_name)">删除</div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="param.offset"
          v-model:page-size="param.limit"
          :page-sizes="[10, 20, 50, 100]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  #user-info {
    margin-top: 60px;
    color: $text-color;

    .run-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 60px;
      width: calc(100% - 200px);
      position: absolute;
      top: 50px;
      left: 200px;
      background-color: $blank-color;
      z-index: 10;
      .run-name-box {
        color: $main-color;
      }

      .state-box {
        display: flex;
        align-items: center;
        margin-left: 20px;

        .run-label {
          font-size: 16px;
          font-weight: bold;
          margin-right: 16px;
        }
        .el-select {
          width: 100px;
        }
        .fleet {
          width: 160px;
          margin-left: 10px;
        }
      }
    }
    .basic-info {
      background-color: $blank-color;
      height: 172px;
      border: 1px solid $border-color;
      padding: 30px;

      .basic-title {
        font-size: 14px;
        font-weight: bold;
      }
      .basic-box {
        display: flex;
        flex-wrap: wrap;
        font-size: 14px;
        margin-top: 30px;
      }
      .content-box {
        width: 33.3%;
        display: flex;
        margin-bottom: 30px;
        .in-box {
          display: flex;
          align-items: center;
          min-height: 14px;
          line-height: 14px;
          :deep(.edit) {
            margin-left: 20px;
          }
          :deep(.actions-box) {
            display: flex;
            align-items: center;
            color: $action-color;
            cursor: pointer;
            .line {
              width: 1px;
              height: 14px;
              background-color: $action-color;
              margin: 0 10px;
            }
            .actions-details:hover {
              color: $main-color;
            }
            .actions-delete:hover {
              color: $main-color;
            }
          }
        }
        .content-label {
          width: 130px;
          margin-right: 30px;
          color: $action-color;
        }
        .content-text {
          color: $text-color;
          word-break: break-all;
        }
      }
    }
    .insert-table {
      margin-top: 20px;
    }
    .insert-info {
      margin-top: 20px;
      padding: 30px;
      background-color: $blank-color;
      border: 1px solid $border-color;
      .insert-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .insert-title {
          font-size: 14px;
          font-weight: bold;
        }
        .btn {
          width: 100px;
          height: 30px;
        }
      }
    }
    .demo-pagination-block {
      margin-top: 20px;
      position: relative;
      .el-pagination {
        justify-content: flex-end;
      }
      :deep(.el-pagination__total) {
        position: absolute;
        left: 0;
      }
      :deep(.el-pagination__sizes) {
        position: absolute;
        left: 58px;
      }
      :deep(.btn-next) {
        min-width: 28px;
        height: 28px;
        background: $blank-color;
        border: 1px solid $border-color;
        color: $text-color;
      }
      :deep(.btn-next:hover) {
        background: $bac-color;
      }
      :deep(.btn-prev) {
        min-width: 28px;
        height: 28px;
        background: $blank-color;
        border: 1px solid $border-color;
        color: $text-color;
      }
      :deep(.btn-prev:hover) {
        background: $bac-color;
      }
      :deep(.el-pager) {
        li {
          padding: 0;
          min-width: 28px;
        }
        .number,
        .more {
          height: 28px;
          background: $blank-color;
          border: 1px solid $border-color;
          color: $text-color;
        }
        .number:hover,
        .more:hover {
          background: $bac-color;
        }
        .is-active {
          border-color: $main-color;
          color: $main-color;
          background: $bac-color;
          font-weight: normal;
        }
      }
    }
    :deep(.el-table) {
      border-radius: 2px;
      font-size: 14px;
      color: $text-color;
      tr {
        border-color: $border-color;
        height: 78px;
      }
      thead > tr:first-child {
        height: 36px;
      }
      .el-table__cell {
        border-right: none;
      }
    }

    :deep(.toDetails) {
      color: $main-color;
      cursor: pointer;
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    :deep(.toDetails:hover) {
      text-decoration: underline;
    }
    :deep(.id-box) {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    :deep(.cell) {
      padding: 0 30px 0 20px;
    }
    :deep(.actions-box) {
      display: flex;
      align-items: center;
      color: $action-color;
      cursor: pointer;
      .line {
        width: 1px;
        height: 14px;
        background-color: $action-color;
        margin: 0 10px;
      }
      .actions-details:hover {
        color: $main-color;
      }
      .actions-delete:hover {
        color: $main-color;
      }
    }
  }
</style>
